<template>
  <el-dialog
    v-model="visible"
    :close-on-click-modal="false"
    @close="handleClose"
    width="680px"
    class="unified-dialog"
    append-to-body
  >
    <template #header>
      <DialogHeader
        icon="Setting"
        :title="isEdit ? '编辑配置' : '新增配置'"
        :description="isEdit ? '修改现有监控配置项' : '创建新的监控配置项'"
        type="primary"
      />
    </template>
    
    <div class="dialog-content">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="0"
        class="config-form"
      >
        <!-- 基础信息 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><Document /></el-icon>
            <span>基础信息</span>
          </div>
          
          <div class="form-grid">
            <div class="form-item-wrapper full-width">
              <label class="form-label">
                <span class="label-text">配置键名</span>
                <span class="required-mark">*</span>
              </label>
              <el-form-item prop="config_key">
                <el-input
                  v-model="formData.config_key"
                  placeholder="如：flink.job.timeout"
                  :disabled="isEdit"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Key /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </div>

            <div class="form-item-wrapper">
              <label class="form-label">
                <span class="label-text">配置分组</span>
                <span class="required-mark">*</span>
              </label>
              <el-form-item prop="config_group">
                <el-select
                  v-model="formData.config_group"
                  placeholder="选择或输入分组"
                  filterable
                  allow-create
                  default-first-option
                  popper-class="batch-dialog-select-popper"
                  :teleported="true"
                >
                  <el-option
                    v-for="group in availableGroups"
                    :key="group"
                    :label="getGroupName(group)"
                    :value="group"
                  />
                </el-select>
              </el-form-item>
            </div>

            <div class="form-item-wrapper">
              <label class="form-label">
                <span class="label-text">配置类型</span>
                <span class="required-mark">*</span>
              </label>
              <el-form-item prop="config_type">
                <el-select v-model="formData.config_type" placeholder="选择类型" popper-class="batch-dialog-select-popper" :teleported="true">
                  <el-option label="字符串" value="string" />
                  <el-option label="整数" value="int" />
                  <el-option label="浮点数" value="float" />
                  <el-option label="布尔值" value="boolean" />
                  <el-option label="JSON" value="json" />
                  <el-option label="列表" value="list" />
                </el-select>
              </el-form-item>
            </div>
          </div>

          <div class="form-grid">
            <div class="form-item-wrapper full-width">
              <label class="form-label">
                <span class="label-text">配置值</span>
                <span class="required-mark">*</span>
                <el-tag v-if="formData.is_sensitive" size="small" type="warning" style="margin-left: 8px;">
                  <el-icon><Lock /></el-icon>
                  敏感信息
                </el-tag>
              </label>
              <el-form-item prop="config_value">
                <el-input
                  v-model="formData.config_value"
                  :type="showPassword ? 'text' : (formData.is_sensitive ? 'password' : 'text')"
                  :autosize="{ minRows: 2, maxRows: 6 }"
                  :placeholder="getValuePlaceholder()"
                  clearable
                  show-word-limit
                >
                  <template #prefix>
                    <el-icon><Edit /></el-icon>
                  </template>
                  <template #suffix v-if="formData.is_sensitive">
                    <el-icon 
                      @click="showPassword = !showPassword" 
                      style="cursor: pointer;"
                    >
                      <component :is="showPassword ? 'View' : 'Hide'" />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </div>

            <div class="form-item-wrapper full-width">
              <label class="form-label">
                <span class="label-text">默认值</span>
              </label>
              <el-form-item prop="default_value">
                <el-input
                  v-model="formData.default_value"
                  placeholder="配置的默认值"
                  clearable
                />
              </el-form-item>
            </div>
          </div>

          <div class="form-grid">
            <div class="form-item-wrapper full-width">
              <label class="form-label">
                <span class="label-text">描述</span>
              </label>
              <el-form-item prop="description">
                <el-input
                  v-model="formData.description"
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  placeholder="配置项的说明"
                  maxlength="255"
                  show-word-limit
                />
              </el-form-item>
            </div>
          </div>
        </div>

        <!-- 高级选项 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><Tools /></el-icon>
            <span>高级选项</span>
          </div>

          <div class="form-grid">
            <div class="form-item-wrapper full-width">
              <label class="form-label">
                <span class="label-text">验证规则</span>
              </label>
              <el-form-item prop="validation_rule">
                <el-input
                  v-model="formData.validation_rule"
                  placeholder="如：^[0-9]+$（数字）"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Check /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </div>

            <div class="form-item-wrapper">
              <label class="form-label">
                <span class="label-text">排序顺序</span>
              </label>
              <el-form-item prop="sort_order">
                <el-input-number
                  v-model="formData.sort_order"
                  :min="0"
                  :max="9999"
                  controls-position="right"
                  style="width: 100%;"
                />
              </el-form-item>
            </div>
          </div>

          <div class="form-grid switch-grid">
            <div class="form-item-wrapper">
              <label class="form-label">
                <span class="label-text">是否必填</span>
              </label>
              <el-form-item>
                <el-switch v-model="formData.is_required" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </div>

            <div class="form-item-wrapper">
              <label class="form-label">
                <span class="label-text">
                  <el-icon><Lock /></el-icon>
                  敏感信息
                </span>
              </label>
              <el-form-item>
                <el-switch v-model="formData.is_sensitive" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </div>

            <div class="form-item-wrapper">
              <label class="form-label">
                <span class="label-text">
                  <el-icon><Warning /></el-icon>
                  需要重启
                </span>
              </label>
              <el-form-item>
                <el-switch v-model="formData.restart_required" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </div>

            <div class="form-item-wrapper">
              <label class="form-label">
                <span class="label-text">是否启用</span>
              </label>
              <el-form-item>
                <el-switch v-model="formData.is_active" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </div>
          </div>

          <!-- 提示信息 -->
          <el-alert
            v-if="formData.restart_required"
            type="warning"
            :closable="false"
            show-icon
            style="margin-top: 12px;"
          >
            <template #title>
              修改此配置后需要重启系统才能生效
            </template>
          </el-alert>
        </div>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          <el-icon><Check /></el-icon>
          {{ isEdit ? '保存' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Setting, Document, Key, Edit, Lock, Hide, View, Tools, Check, Warning
} from '@element-plus/icons-vue'
import api from '@/utils/api'
import { createLogger } from '@/utils/logger'
import DialogHeader from '@/components/DialogHeader.vue'

const componentLogger = createLogger('ConfigEditDialog')

// 配置分组中文映射
const groupNameMap = {
  'general': '通用配置',
  'alert': '告警配置',
  'database': '数据库配置',
  'flink': 'Flink配置',
  'log': '日志配置',
  'monitor': '监控配置',
  'retention': '保留策略',
  'savepoint': 'Savepoint配置'
}

// 获取分组中文名
const getGroupName = (group) => {
  return groupNameMap[group] || group
}

const props = defineProps({
  modelValue: Boolean,
  configData: Object,
  availableGroups: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const formRef = ref(null)
const submitting = ref(false)
const showPassword = ref(false)

const isEdit = computed(() => !!props.configData?.id)

const formData = ref({
  config_key: '',
  config_group: 'general',
  config_value: '',
  config_type: 'string',
  default_value: '',
  validation_rule: '',
  is_required: 0,
  is_sensitive: 0,
  restart_required: 0,
  is_active: 1,
  sort_order: 0,
  description: ''
})

const rules = {
  config_key: [
    { required: true, message: '请输入配置键名', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  config_group: [
    { required: true, message: '请选择配置分组', trigger: 'change' }
  ],
  config_value: [
    { required: true, message: '请输入配置值', trigger: 'blur' }
  ],
  config_type: [
    { required: true, message: '请选择配置类型', trigger: 'change' }
  ]
}

const getValuePlaceholder = () => {
  const placeholders = {
    string: '输入字符串值',
    int: '输入整数值',
    float: '输入浮点数值',
    boolean: '输入 true 或 false',
    json: '输入 JSON 格式的配置',
    list: '输入逗号分隔的列表'
  }
  return placeholders[formData.value.config_type] || '输入配置值'
}

watch(() => props.configData, (newVal) => {
  if (newVal) {
    formData.value = {
      ...formData.value,
      ...newVal
    }
    showPassword.value = false
  }
}, { immediate: true, deep: true })

watch(visible, (newVal) => {
  if (!newVal) {
    showPassword.value = false
  }
})

const handleClose = () => {
  formRef.value?.resetFields()
  formData.value = {
    config_key: '',
    config_group: 'general',
    config_value: '',
    config_type: 'string',
    default_value: '',
    validation_rule: '',
    is_required: 0,
    is_sensitive: 0,
    restart_required: 0,
    is_active: 1,
    sort_order: 0,
    description: ''
  }
  showPassword.value = false
  visible.value = false
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    const submitData = { ...formData.value }
    
    // 类型转换
    if (submitData.config_type === 'int') {
      submitData.config_value = String(parseInt(submitData.config_value))
    } else if (submitData.config_type === 'float') {
      submitData.config_value = String(parseFloat(submitData.config_value))
    } else if (submitData.config_type === 'boolean') {
      const val = String(submitData.config_value).toLowerCase()
      if (!['true', 'false', '1', '0'].includes(val)) {
        ElMessage.warning('布尔值只能是 true/false 或 1/0')
        return
      }
    } else if (submitData.config_type === 'json') {
      try {
        JSON.parse(submitData.config_value)
      } catch (e) {
        ElMessage.warning('JSON 格式不正确')
        return
      }
    }
    
    if (isEdit.value) {
      await api.put(`/flink-monitor-config/${submitData.id}`, submitData)
      ElMessage.success('配置更新成功')
    } else {
      await api.post('/flink-monitor-config', submitData)
      ElMessage.success('配置创建成功')
    }
    
    emit('success')
    handleClose()
  } catch (error) {
    componentLogger.error('提交配置失败', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error(isEdit.value ? '更新配置失败' : '创建配置失败')
    }
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.dialog-content {
  max-height: 65vh;
  overflow-y: auto;
}

.config-form {
  padding: 0;
}

.form-section {
  margin-bottom: 24px;
  background: var(--el-bg-color-page);
  border-radius: 8px;
  padding: 16px;
}

.form-section:last-child {
  margin-bottom: 0;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.section-title .el-icon {
  color: var(--el-color-primary);
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.form-item-wrapper {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item-wrapper.full-width {
  grid-column: 1 / -1;
}

.form-label {
  display: flex;
  align-items: center;
  font-size: 13px;
  font-weight: 500;
  color: var(--el-text-color-regular);
}

.label-text {
  display: flex;
  align-items: center;
  gap: 4px;
}

.required-mark {
  color: var(--el-color-danger);
  margin-left: 2px;
}

.form-item-wrapper :deep(.el-form-item) {
  margin-bottom: 0;
}

.switch-grid {
  grid-template-columns: repeat(4, 1fr);
}

.switch-grid .form-item-wrapper {
  align-items: flex-start;
}

.option-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>

